package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrdersTask {

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 超时订单定时处理
     */
    @Scheduled(cron = "0 * * * * ?") //每分钟检查一次
    //@Scheduled(cron = "1/5 * * * * ? ")
    public void OrderTimeOutProcess(){
        log.info("超时订单定时处理");
        //检查待付款状态，并且下单时间在当前时间-15min之前的订单
        LocalDateTime time = LocalDateTime.now();
        time = time.plusMinutes(-15);
        //select * from orders where status = #{} and order_time < #{time}
        List<Orders> ordersList = orderMapper.getByStatusAndOrTimeLt(Orders.PENDING_PAYMENT,time);
        //将这些订单的状态修改为取消
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时取消");
                orderMapper.update(orders);
            }
        }
    }


    /**
     * 一直处于派送中的订单处理
     */
    @Scheduled(cron = "0 0 1 * * ? ") //每天凌晨一点检查一次
    //@Scheduled(cron = "0/5 * * * * ? ")
    public void deliveryOrderProcess(){
        log.info("派送中的订单定时处理");
        //检查派送中状态，并且下单时间在当前时间-60min之前的订单
        LocalDateTime time = LocalDateTime.now();
        time = time.plusMinutes(-60);
        //select * from orders where status = #{} and order_time < #{time}
        List<Orders> ordersList = orderMapper.getByStatusAndOrTimeLt(Orders.DELIVERY_IN_PROGRESS,time);
        //将这些订单的状态修改为完成
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
